/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pkwserver;

import java.security.cert.Certificate;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.ssl.SslFilter;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author Pawel
 */
public class PKWClientHandler extends IoHandlerAdapter {
    
    @Override
    public void sessionOpened(IoSession session) throws Exception {
        // Hello message
         
            Element ss = new Element("session");
            ss.setAttribute("name", "registration");
            Element msg = new Element("msg");
            Document doc = new Document(ss);
            /*Element content = new Element("content");
            content.addContent("HELLO");
            msg.addContent(content);
            ss.addContent(msg);*/
            msg.addContent(MyXmlParser.parseToXmlSimpleObject(new PersonalData("Maciej", "Zgliczynski", "89064243", "223")));
            ss.addContent(msg);
            XMLOutputter out = new XMLOutputter();
            out.setFormat(Format.getPrettyFormat());
            
            /*String str = out.outputString(doc);
            IoBuffer buf = IoBuffer.allocate(str.length()+5);
            buf.putString(str, null);*/
            session.write(out.outputString(doc));
            //session.write("whatever");
    }
    
    @Override
    public void messageReceived(IoSession session, Object message) {
        System.out.println(message.toString());
       try {
            SslFilter sslFilter = (SslFilter) session.getFilterChain().get("sslFilter");
            System.out.println(sslFilter.getSslSession(session).getPeerPrincipal().getName());
           /* Certificate certs[] = sslFilter.getSslSession(session).getPeerCertificates();
            for (Certificate cert : certs){
                System.out.println(cert.toString());
            }*/
        } catch (Exception ex) {
            Logger.getLogger(PKWProtocolHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
